package acwing;

import java.io.*;
import java.util.*;

public class ac850 {
    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    static final int N = 150010, INF = 0x3f3f3f3f;
    static int n, m, idx;
    static int[] h = new int[N], e = new int[N], ne = new int[N], w = new int[N], d = new int[N];
    static boolean[] st = new boolean[N];

    static int cin() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    static void add(int a, int b, int c) {
        e[idx] = b;
        ne[idx] = h[a];
        w[idx] = c;
        h[a] = idx ++ ;
    }

    static int dijkstra() {
        Queue<pii> q = new PriorityQueue<>(Comparator.comparingInt(o -> o.a));
        d[1] = 0;
        q.offer(new pii(0, 1));
        while (!q.isEmpty()) {
            pii t = q.poll();
            if (st[t.b]) continue;
            st[t.b] = true;
            for (int i = h[t.b]; i != -1; i = ne[i]) {
                int j = e[i];
                if (d[j] > d[t.b] + w[i]) {
                    d[j] = d[t.b] + w[i];
                    q.offer(new pii(d[j], j));
                }
            }
        }
        if (d[n] == INF) return -1;
        return d[n];
    }

    public static void main(String[] args) throws IOException {
        n = cin(); m = cin();
        Arrays.fill(h, -1);
        Arrays.fill(d, INF);
        while (m -- > 0) {
            int x = cin(), y = cin(), z = cin();
            add(x, y, z);
        }
        out.println(dijkstra());
        out.close();
    }
}
class pii {
    int a;
    int b;
    pii(int a, int b) {
        this.a = a;
        this.b = b;
    }
}